package org.linlinjava.litemall.wx.web;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.google.gson.JsonObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.VolunteerService;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.vo.LdOrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import static org.linlinjava.litemall.wx.util.WxResponseCode.AUTH_INVALID_ACCOUNT;

@RestController
@RequestMapping("wx/yigong")
public class WxThirdPartYigongController {
    private final Log logger = LogFactory.getLog(WxThirdPartYigongController.class);

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private VolunteerService volunteerService;

    @RequestMapping("/userExist")
    public Object userExist(@LoginUser Integer userId){
        LitemallUser user = userService.findById(userId);
        if (user==null || user.getMobile().equals(""))
            return ResponseUtil.fail(503,"业务不支持，您还未绑定手机号，请绑定手机号");

        JsonObject jsonObject = volunteerService.userInfo(user.getMobile());
        if("true".equals(jsonObject.get("result").getAsString())) {
            return ResponseUtil.ok();
        }else{
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "义工用户不存在");
        }
    }

    @RequestMapping("/integral")
    public Object getIntegral(@LoginUser Integer userId){
        LitemallUser user = userService.findById(userId);
        if (user==null || user.getMobile().equals(""))
            return ResponseUtil.fail(503,"业务不支持，您还未绑定手机号，请绑定手机号");

        JsonObject jsonObject = volunteerService.userInfo(user.getMobile());
        if("true".equals(jsonObject.get("result").getAsString())) {
            return ResponseUtil.ok(jsonObject.get("data").getAsJsonObject().get("integrals").getAsDouble());
        }else{
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "义工用户不存在");
        }

    }


    @PostMapping("/pay")
    public Object pay(@LoginUser Integer userId, @RequestBody String body){
        LitemallUser user = userService.findById(userId);
        if (user==null || user.getMobile().equals("")) {
            return ResponseUtil.fail(503, "业务不支持，您还未绑定手机号，请绑定手机号");
        }
        Integer orderId =  JacksonUtil.parseInteger(body, "orderId");
        LitemallOrder litemallOrder = orderService.findById(Integer.valueOf(orderId));
        if(!litemallOrder.getAllowIntegral()){
            return ResponseUtil.fail(503, "业务不支持，该订单无法使用积分支付");
        }
        BigDecimal integrals = litemallOrder.getIntegralPrice();
        JsonObject jsonObject = volunteerService.pay(user.getMobile(), integrals, litemallOrder.getId().toString(),
                "购买商品(订单号:" + litemallOrder.getOrderSn() + ")" );
        if("true".equals(jsonObject.get("result").getAsString())){
            litemallOrder.setPayCategory(OrderUtil.INTEGRAL_PAY);
            litemallOrder.setPayTime(LocalDateTime.now());
            litemallOrder.setOrderStatus(OrderUtil.STATUS_PAY);
            litemallOrder.setPayId(jsonObject.get("data").getAsString());
            if (orderService.updateWithOptimisticLocker(litemallOrder) == 0) {
                return WxPayNotifyResponse.fail("更新数据已失效");
            }
            //TODO 发送邮件和短信通知，这里采用异步发送
            // 订单支付成功以后，会发送短信给用户，以及发送邮件给管理员
            notifyService.notifyMail("新订单通知", litemallOrder.toString());
            // 这里微信的短信平台对参数长度有限制，所以将订单号只截取后6位
            notifyService.notifySmsTemplateSync(litemallOrder.getMobile(), NotifyType.PAY_SUCCEED, new String[]{litemallOrder.getOrderSn().substring(8, 14)});

        }else{
            return ResponseUtil.fail(503, "" + jsonObject.get("message").getAsString());
        }
        return ResponseUtil.ok();
    }


    @RequestMapping("/createUser")
    public Object createUser(@LoginUser Integer userId){
        LitemallUser user = userService.findById(userId);
        if (user==null || user.getMobile().equals(""))
            return ResponseUtil.fail(503,"业务不支持，您还未绑定手机号，请绑定手机号");
        JsonObject jsonObject = volunteerService.createUser(user.getMobile());
        return ResponseUtil.ok(jsonObject);
    }

}
